package main

import (
	"fmt"
	"net/http"

	"gitee.com/xgh2012/api-core/coreDb"
	"gitee.com/xgh2012/api-core/coreGinServer"
	"gitee.com/xgh2012/api-core/coreUtils"
	"gitee.com/xgh2012/api-core/coreZapLog"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

const (
	serviceName = "测试系统"
	service     = "test"
)

var (
	RedisClient *redis.Client
	DbClient    *gorm.DB
	err         error
)

func main() {
	// 初始化配置
	coreUtils.InitConfig(service)

	workerId := viper.GetInt("worker_id")
	if workerId <= 0 {
		panic("env.yaml 缺少worker_id")
	}

	//初始化订单号生成器
	coreUtils.InitOrderGenerator(int64(workerId))

	//初始化IP库
	coreUtils.InitChunZhenIp()

	//初始化redis---------开始 	TODO 根据项目配置
	cfg := coreDb.RedisConfig{
		Host:     viper.GetString("redis_master_self.host"),
		Port:     viper.GetString("redis_master_self.port"),
		Password: viper.GetString("redis_master_self.password"),
		DB:       0,
	}
	RedisClient = coreDb.InitRedis(cfg)

	//初始化redis---------结束

	//初始化数据库---------开始  TODO 根据项目配置
	cfgDatabase := &coreDb.DatabaseCfg{
		Username: viper.GetString("database.username"),
		Password: viper.GetString("database.password"),
		Host:     viper.GetString("database.hostname"),
		Port:     viper.GetString("database.hostport"),
		Database: viper.GetString("database.database"),
		Charset:  viper.GetString("database.charset"),
		LogLevel: viper.GetString("database.log_level"),
		PoolSet: coreDb.PoolSet{
			MaxIdleConn: viper.GetInt("database.pool_maxIdleConn"),
			MaxOpenConn: viper.GetInt("database.pool_maxOpenConn"),
			MaxLifeTime: viper.GetInt("database.pool_maxLifeTime"),
			MaxIdleTime: viper.GetInt("database.pool_maxIdleTime"),
		},
	}
	DbClient, err = coreDb.ConnectDatabase(cfgDatabase)
	if err != nil {
		coreZapLog.Logger.Error("初始化数据库出错", zap.Error(err), zap.String("database", viper.GetString("database.database")))
		panic(err)
	}
	//初始化数据库---------结束

	//启动服务器
	srv := coreGinServer.StartSever(viper.GetInt("ip_port"), serviceName, registerRoutes)

	//监听关闭服务器
	coreGinServer.StopServer(srv, serviceName)
}

// registerRoutes 注册路由
func registerRoutes(engine *gin.Engine) {
	engine.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, fmt.Sprintf("Index %s-%s", viper.GetString("serenv"), viper.GetString("serverno")))
	})
}
